---
import Layout from '@/layouts/Layout.astro'
import { porra } from '@/consts/pageTitles'
import { getSession } from 'auth-astro/server'
import { COMBATS } from '@/consts/combats'
import { getBoxerById } from '@/lib/boxers'
import { getAllPredictions, type CombatPrediction } from '@/lib/predictions'
import PredictionBar from '@/components/PredictionBar.astro'

const description =
  'Participa en la porra oficial de La Velada del Año V y haz tus predicciones sobre los combates de Ibai Llanos y creadores de contenido.'
const canonical = 'https://www.infolavelada.com/porra'

// Obtener la sesión del usuario
const session = await getSession(Astro.request)
const user = session?.user

// Obtener predicciones actuales
let predictions: CombatPrediction[] = []
try {
  predictions = await getAllPredictions()
} catch (error) {
  console.error('Error al obtener predicciones:', error)
}

// Obtener votos del usuario si está autenticado
let userVotes: Array<{ combat_id: string; fighter_id: string; created_at: string }> = []
if (user) {
  try {
    const response = await fetch(`${Astro.url.origin}/api/predictions?user_predictions=true`, {
      headers: {
        Cookie: Astro.request.headers.get('cookie') || '',
      },
    })
    if (response.ok) {
      const data = await response.json()
      userVotes = data.predictions || []
    }
  } catch (error) {
    console.error('Error al obtener votos del usuario:', error)
  }
}

export const prerender = false
---

<Layout title={porra} description={description} canonical={canonical}>
  <section
    class="mx-auto mt-24 flex min-h-screen w-full flex-col items-center justify-start gap-4 px-4"
  >
    <h2
      class="mt-10 bg-gradient-to-r from-sky-100 to-pink-300 bg-clip-text text-center text-2xl font-bold text-transparent drop-shadow-[0_1.2px_1.2px_rgba(0,0,0,0.8)]"
    >
      RESULTADOS DE LA PORRA
    </h2>

    <div
      class="mt-4 rounded-lg bg-red-600/80 px-4 py-2 text-center text-sm text-white backdrop-blur-sm"
    >
      ¡⏰ La votación ha finalizado!
    </div>

    {
      user && (
        <div class="mt-4 flex items-center gap-4 rounded-lg bg-black/30 px-6 py-4 shadow-lg backdrop-blur-sm">
          {user.image && (
            <img src={user.image} alt={`Avatar de ${user.name}`} class="size-14 rounded-full" />
          )}
          <div class="flex flex-col lowercase">
            <span class="text-white">¡Hola, {user.name}!</span>
            <span class="text-sm text-white/80">Estos fueron tus votos en la porra</span>
          </div>
          <button
            id="logout-btn"
            class="ml-4 cursor-pointer rounded-lg bg-red-700 px-4 py-2 text-sm font-medium lowercase text-white transition-all duration-300 hover:scale-105 hover:bg-red-800"
          >
            Cerrar sesión
          </button>
        </div>
      )
    }

    <div class="flex w-full flex-col items-center text-center">
      <div
        id="combats-container"
        class="relative mx-auto mb-24 mt-10 grid max-w-7xl grid-cols-1 gap-4 p-6 md:gap-8"
      >
        {
          COMBATS.toReversed().map(({ id, number, fighters, title }, index) => (
            <article class:list={['inline-block', index === 0 ? 'col-span-1' : 'md:col-span-1']}>
              <div
                class:list={[
                  'combat relative flex w-full',
                  index === 0 ? 'h-[50vh] sm:h-[60vh] md:h-[70vh]' : 'h-[40vh] sm:h-[50vh]',
                  index % 2 === 0 && index !== 0 ? '' : index !== 0 ? '' : '',
                  'animate-delay-200 lg',
                ]}
              >
                {fighters.map((fighter, fighterIndex) => {
                  // Verificar si el usuario ya votó en este combate (solo si está autenticado)
                  const userVoteForCombat = user
                    ? userVotes.find((vote) => vote.combat_id === id)
                    : undefined
                  const hasUserVoted = userVoteForCombat !== undefined
                  const isUserVoteForThisFighter = userVoteForCombat?.fighter_id === fighter

                  return (
                    <div
                      class:list={[
                        'fighter-result group relative z-20 flex size-96 h-full w-1/2 flex-col items-center transition-all duration-300',
                      ]}
                      data-combat-id={id}
                      data-fighter-id={fighter}
                      data-fighter-index={fighterIndex}
                      data-user-vote={isUserVoteForThisFighter}
                      data-user-has-voted={hasUserVoted}
                    >
                      <img
                        src={`/images/fighters/combat/${fighter}.webp`}
                        class:list={[
                          'mask-fade-bottom group-hover:contrast-110 size-96 h-full w-full object-contain object-bottom transition-all duration-300 group-hover:brightness-110',
                        ]}
                        alt={`Imagen de ${fighter}`}
                        transition:name={`combat-img:${fighter}`}
                      />

                      {user && (
                        <div
                          class:list={[
                            'fighter-user-vote pointer-events-none absolute bottom-4 left-1/2 z-50 -translate-x-1/2 rounded-lg bg-green-600 px-2 py-1 text-[10px] font-bold uppercase text-white opacity-0 shadow-lg transition-opacity duration-300',
                          ]}
                        >
                          ¡Tu voto!
                        </div>
                      )}
                    </div>
                  )
                })}

                <div class="pointer-events-none absolute bottom-0 z-30 flex h-auto w-full flex-col items-center justify-center p-8 transition-transform">
                  <img
                    src={`/images/fighters/combat/${fighters[0]}-vs-${fighters[1]}.webp`}
                    class:list={['transform-3d z-50', 'h-40 object-contain md:h-64']}
                    alt={`${fighters[0]} contra ${fighters[1]}`}
                    transition:name={`vs:${fighters[0]}-${fighters[1]}`}
                  />
                </div>
              </div>
              <div class="relative mt-24 block">
                <PredictionBar
                  disableLink={true}
                  combatId={id}
                  overlay={true}
                  fighter1={{
                    id: getBoxerById(fighters[0])?.id || '',
                    name: getBoxerById(fighters[0])?.name || '',
                    percentage: 60,
                  }}
                  fighter2={{
                    id: getBoxerById(fighters[1])?.id || '',
                    name: getBoxerById(fighters[1])?.name || '',
                    percentage: 40,
                  }}
                  totalVotes={100}
                />
              </div>
            </article>
          ))
        }
      </div>
    </div>
  </section>
</Layout>

<script>
  import { getPredictionsForPage } from '@/lib/get-predictions-for-page'
  import { signIn, signOut } from 'auth-astro/client'
  import confetti from 'canvas-confetti'

  document.addEventListener('astro:page-load', async () => {
    const logoutBtn = document.getElementById('logout-btn')
    if (logoutBtn) {
      logoutBtn.addEventListener('click', async () => {
        try {
          await signOut()
        } catch (error) {
          console.error('Error al cerrar sesión:', error)
        }
      })
    }

    getPredictionsForPage()

    // La votación ha finalizado - solo mostrar resultados
    console.log('La votación ha finalizado. Solo se muestran los resultados.')
  })
</script>

<style>
  /* Estilos para resultados de la porra (votación cerrada) */

  /* Luchador votado por el usuario */
  .fighter-result[data-user-vote='true'] {
    pointer-events: none;

    & .fighter-user-vote {
      opacity: 1;
    }

    & img {
      filter: sepia(100%) saturate(200%) hue-rotate(60deg);
    }

    & .fighter-info-text {
      display: none;
    }
  }

  /* Luchador no votado cuando el usuario ya votó en este combate */
  .fighter-result[data-user-has-voted='true']:not([data-user-vote='true']) img {
    filter: sepia(100%) saturate(300%) hue-rotate(300deg) brightness(0.4) contrast(1);
  }

  /* Estilos para elementos sin votación del usuario */
  .fighter-result:not([data-user-has-voted='true']) .fighter-info-text {
    background: rgb(75 85 99) !important;
  }
</style>
